package leecode.add;

import java.util.ArrayList;
import java.util.List;

public class Solutions {

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1), l2 = new ListNode(1);
        l2.next = new ListNode(9);
        l2.next.next = new ListNode(9);
//        l2.next.next.next = new ListNode(9);
//        l2.next.next.next.next = new ListNode(9);
//        l2.next.next.next.next.next = new ListNode(9);
//        l2.next.next.next.next.next.next = new ListNode(9);
//        l2.next.next.next.next.next.next.next = new ListNode(9);
//        l2.next.next.next.next.next.next.next.next= new ListNode(9);
//        l2.next.next.next.next.next.next.next.next.next= new ListNode(9);

        addTwoNumbers(l1, l2);
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        List<Integer> listA = new ArrayList<>();
        List<Integer> listB = new ArrayList<>();
        ListNode headA = l1;
        ListNode headB = l2;
        while (headA != null) {
            listA.add(headA.val);
            headA = headA.next;
        }
        while (headB != null) {
            listB.add(headB.val);
            headB = headB.next;
        }
        int lengthA = listA.size();
        int lengthB = listB.size();
        int diff = Math.abs(lengthA - lengthB);
        dealZero(lengthA - lengthB > 0 ? listB : listA, diff);
        return add(listA, listB);
    }

    private static ListNode add(List<Integer> listA, List<Integer> listB) {
        List<Integer> resList = new ArrayList<>();
        int more = 0;
        for (int i = 0; i < listA.size(); i++) {
            int a = listA.get(i);
            int b = listB.get(i);
            int perSum = a + b + more;
            int num = perSum % 10;
            more = perSum / 10;
            resList.add(num);
        }
        ListNode res = new ListNode();
        ListNode head = res;
        for (int i = 0; i < resList.size(); i++) {
            head.val = resList.get(i);
            if (i != resList.size() - 1) {
                head.next = new ListNode();
            }
            head = head.next;
        }
        return res;
    }

    private static void dealZero(List<Integer> list, int diff) {
        for (int i = 0; i < diff; i++) {
            list.add(0);
        }
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
